﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using ZWZTools.Model;

namespace ZWZTools.Common
{
    public class AppSettings
    {
        /// <summary>
        /// 上次使用的线路
        /// </summary>
        public AnalysisUrl LastUrl { get; set; }
        public static AppSettings Instance { get; private set; } = null;
        private AppSettings() { }
        static AppSettings()
        {
            try
            {
                var dir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
                var fileName = dir + "\\Config\\AppSettings.json";
                if (File.Exists(fileName))
                {
                    var josnStr = File.ReadAllText(fileName);
                    Instance = JsonConvert.DeserializeObject<AppSettings>(josnStr);
                }
                else
                {
                    Instance = new AppSettings();
                    if (!Directory.Exists(dir + "\\Config"))
                    {
                        Directory.CreateDirectory(dir + "\\Config");
                    }
                    var jsonStr = JsonConvert.SerializeObject(Instance, Formatting.Indented);
                    File.WriteAllText(fileName, jsonStr);
                }
            }
            catch (Exception)
            {
                InitDefaultSetting();
            }
        }
        /// <summary>
        /// 生成默认配置并保存文件
        /// </summary>
        private static void InitDefaultSetting()
        {
            var dir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            var fileName = dir + "\\Config\\AppSettings.json";
            Instance = new AppSettings();
            if (!Directory.Exists(dir + "\\Config"))
            {
                Directory.CreateDirectory(dir + "\\Config");
            }
            var jsonStr = JsonConvert.SerializeObject(Instance, Formatting.Indented);
            File.WriteAllText(fileName, jsonStr);
        }
        /// <summary>
        /// 保存配置文件
        /// </summary>
        public void Save()
        {
            var dir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            var fileName = dir + "\\Config\\AppSettings.json";
            if (!Directory.Exists(dir + "\\Config"))
            {
                Directory.CreateDirectory(dir + "\\Config");
            }
            var jsonStr = JsonConvert.SerializeObject(Instance, Formatting.Indented);
            File.WriteAllText(fileName, jsonStr);
        }
    }
}
